<template>
  <view class="register-page">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">手动登记收文</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-container">
      <view class="form-card">
        <view class="card-title">阳泉市卫生健康委员会文件批阅卡</view>

        <!-- 来文单位 -->
        <view class="form-item">
          <text class="form-label">来文单位</text>
          <input
            class="form-input-underline"
            v-model="formData.sourceCompanyName"
            placeholder="请输入来文单位"
          />
        </view>

        <!-- 文件字号 -->
        <view class="form-item">
          <text class="form-label">文件字号</text>
          <input
            class="form-input-underline"
            v-model="formData.receiveDocumentSymbol"
            placeholder="请输入文件字号"
          />
        </view>

        <!-- 紧急程度 -->
        <view class="form-item">
          <text class="form-label">紧急程度</text>
          <picker
            mode="selector"
            :value="urgencyIndex"
            :range="urgencyOptions"
            @change="onUrgencyChange"
          >
            <view class="picker-input-underline">
              {{ urgencyOptions[urgencyIndex] || '请选择紧急程度' }}
            </view>
          </picker>
        </view>

        <!-- 收文时间 -->
        <view class="form-item">
          <text class="form-label">收文时间</text>
          <picker mode="date" :value="formData.receiveDocumentTime" @change="onDateChange">
            <view class="picker-input-underline">
              {{ formData.receiveDocumentTime || '请选择收文时间' }}
            </view>
          </picker>
        </view>

        <!-- 收文编号 -->
        <view class="form-item">
          <text class="form-label">收文编号</text>
          <input
            class="form-input-underline"
            v-model="formData.receiveDocumentNumber"
            placeholder="请输入收文编号"
          />
        </view>

        <!-- 文件标题 -->
        <view class="form-item">
          <text class="form-label">文件标题</text>
          <textarea
            class="form-textarea-underline"
            v-model="formData.sourceDocumentTitle"
            placeholder="请输入文件标题"
            :maxlength="200"
          />
        </view>

        <!-- 红头文件 -->
        <view class="form-item">
          <view class="form-label-wrapper">
            <text class="form-label">红头文件以及附件</text>
            <text class="form-label-tip">(第一个文件为红头文件，最多9个，每个最大100MB)</text>
          </view>
          <view class="upload-section">
            <yt-upload
              ref="ytUploadRef"
              childId="registerUpload"
              width="100%"
              height="120rpx"
              :option="uploadOption"
              :count="9"
              :size="100"
              :instantly="false"
              :debug="true"
              formats=""
              @change="onFileChange"
              @progress="onUploadProgress"
              @uploadEnd="onUploadEnd"
            >
              <view class="upload-btn-slot">
                <text class="upload-icon">📁</text>
                <text class="upload-text">选择文件</text>
              </view>
            </yt-upload>

            <!-- 文件列表 -->
            <view class="file-list" v-if="fileList.length > 0">
              <view class="file-item" v-for="file in fileList" :key="file.name">
                <view class="file-info">
                  <text class="file-name">{{ file.name }}</text>
                  <text class="file-size">{{ formatFileSize(file.size) }}</text>
                  <text class="file-status" :class="'status-' + file.type">
                    {{ getStatusText(file.type) }}
                  </text>
                </view>
                <text class="file-delete" @click="removeFile(file.name)">×</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <view class="action-btn cancel" @click="goBack">
        <text class="btn-text">取消</text>
      </view>
      <view class="action-btn primary" @click="saveDraft">
        <text class="btn-text">保存草稿</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { createReceiveDraft } from '@/Api/receive'
import { useMemberStore } from '@/stores/modules/member'
import envConfig from '@/config/env'

// 表单数据
const formData = reactive({
  sourceCompanyName: '',
  receiveDocumentSymbol: '',
  receiveDocumentNumber: '',
  sourceDocumentTitle: '',
  receiveDocumentTime: '',
  urgencyLevel: 'normal',
  remark: '',
})

// 紧急程度选项
const urgencyOptions = ['普通', '紧急', '特急']
const urgencyIndex = ref(0)

// 文件列表
const fileList = ref<any[]>([])
const filesMap = ref(new Map())

// yt-upload 组件引用
const ytUploadRef = ref<any>(null)

// #ifndef H5
// APP 端上传状态
const uploadStatus = ref({
  isUploading: false,
  uploadedCount: 0,
  totalCount: 0,
  firstResponse: null as any,
  documentId: null as any,
  resolve: null as any,
  reject: null as any,
})
// #endif

// yt-upload 上传配置
const uploadOption = computed(() => {
  const memberStore = useMemberStore()
  const userInfo = memberStore.profile
  const token = uni.getStorageSync('token')

  // #ifdef H5
  // H5 使用原接口（一次性上传所有文件）
  return {
    url: `${envConfig.baseUrl}/receive/distributes/create-with-files`,
    name: 'files',
    header: {
      satoken: token || '',
      Authorization: token ? `Bearer ${token}` : '',
      'X-User-Id': userInfo?.id ? String(userInfo.id) : '',
      'X-Username': userInfo?.username ? encodeURIComponent(userInfo.username) : '',
      'X-Real-Name': userInfo?.nickname
        ? encodeURIComponent(userInfo.nickname || userInfo.realName || userInfo.name || '')
        : '',
      'X-Company-Id': userInfo?.companyId ? String(userInfo.companyId) : '',
      'X-Company-Name': userInfo?.companyName ? encodeURIComponent(userInfo.companyName || '') : '',
    },
    formData: {
      data: '',
    },
  }
  // #endif

  // #ifndef H5
  // APP 使用新接口（逐个上传）
  // eslint-disable-next-line no-unreachable
  return {
    url: `${envConfig.baseUrl}/receive/distributes/create-with-file-step`,
    name: 'file',
    header: {
      satoken: token || '',
      Authorization: token ? `Bearer ${token}` : '',
      'X-User-Id': userInfo?.id ? String(userInfo.id) : '',
      'X-Username': userInfo?.username ? encodeURIComponent(userInfo.username) : '',
      'X-Real-Name': userInfo?.nickname
        ? encodeURIComponent(userInfo.nickname || userInfo.realName || userInfo.name || '')
        : '',
      'X-Company-Id': userInfo?.companyId ? String(userInfo.companyId) : '',
      'X-Company-Name': userInfo?.companyName ? encodeURIComponent(userInfo.companyName || '') : '',
    },
    formData: {
      data: '',
    },
  }
  // #endif
})

// 紧急程度变化
const onUrgencyChange = (e: any) => {
  urgencyIndex.value = e.detail.value
  const urgencyMap = ['normal', 'urgent', 'critical']
  formData.urgencyLevel = urgencyMap[e.detail.value]
}

// 日期变化
const onDateChange = (e: any) => {
  formData.receiveDocumentTime = e.detail.value
}

// 文件选择回调
const onFileChange = (files: Map<string, any>) => {
  filesMap.value = files
  fileList.value = Array.from(files.values())
}

// 上传进度回调
const onUploadProgress = (item: any) => {
  filesMap.value.set(item.name, item)
  fileList.value = Array.from(filesMap.value.values())
}

// 上传结束回调
const onUploadEnd = (item: any) => {
  filesMap.value.set(item.name, item)
  fileList.value = Array.from(filesMap.value.values())

  if (item.type === 'fail') {
    uni.showToast({
      title: `${item.name}上传失败`,
      icon: 'none',
      duration: 2000,
    })
  }

  // #ifndef H5
  // APP 端：处理分步上传
  // @ts-ignore
  if (uploadStatus.value.isUploading) {
    // @ts-ignore
    uploadStatus.value.uploadedCount++

    // 第一个文件上传成功后，获取 documentId
    // @ts-ignore
    if (uploadStatus.value.uploadedCount === 1 && item.type === 'success' && item.responseText) {
      try {
        const response = JSON.parse(item.responseText)
        if (response.code === 200 && response.data) {
          const documentId = response.data
          // @ts-ignore
          uploadStatus.value.documentId = documentId
          // @ts-ignore
          uploadStatus.value.firstResponse = response

          // 更新 formData，后续文件传 documentId
          // 多次调用确保 WebView 内部更新完成（解决第二个文件上传时 formData 未更新的问题）
          ytUploadRef.value?.setData('formData', { documentId: String(documentId) })
          setTimeout(() => {
            ytUploadRef.value?.setData('formData', { documentId: String(documentId) })
          }, 50)
          setTimeout(() => {
            ytUploadRef.value?.setData('formData', { documentId: String(documentId) })
          }, 100)
          setTimeout(() => {
            ytUploadRef.value?.setData('formData', { documentId: String(documentId) })
          }, 200)
        }
      } catch (e) {
        console.error('解析响应失败:', e)
      }
    }

    // 所有文件上传完成
    // @ts-ignore
    if (uploadStatus.value.uploadedCount >= uploadStatus.value.totalCount) {
      // @ts-ignore
      uploadStatus.value.isUploading = false

      // @ts-ignore
      if (uploadStatus.value.firstResponse) {
        // @ts-ignore
        uploadStatus.value.resolve?.(uploadStatus.value.firstResponse)
      } else {
        // @ts-ignore
        uploadStatus.value.reject?.(new Error('上传失败'))
      }

      // 重置状态
      // @ts-ignore
      uploadStatus.value.uploadedCount = 0
      // @ts-ignore
      uploadStatus.value.totalCount = 0
      // @ts-ignore
      uploadStatus.value.firstResponse = null
      // @ts-ignore
      uploadStatus.value.documentId = null
      // @ts-ignore
      uploadStatus.value.resolve = null
      // @ts-ignore
      uploadStatus.value.reject = null
    }
  }
  // #endif
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

// 获取文件状态文本
const getStatusText = (type: string): string => {
  const statusMap: Record<string, string> = {
    waiting: '待上传',
    loading: '上传中',
    success: '成功',
    fail: '失败',
  }
  return statusMap[type] || '未知'
}

// 删除文件
const removeFile = (fileName: string) => {
  ytUploadRef.value?.clear(fileName)
}

// 返回上一页
const goBack = () => {
  const pages = getCurrentPages()
  if (pages.length <= 1) {
    uni.reLaunch({ url: '/pages/index/index' })
  } else {
    uni.navigateBack({ delta: 1 })
  }
}

/**
 * H5 平台上传（使用 FormData）
 */
const uploadFilesH5 = async (params: any): Promise<any> => {
  // #ifdef H5
  return new Promise((resolve, reject) => {
    const formData = new FormData()
    formData.append('data', JSON.stringify(params))

    fileList.value.forEach((item) => {
      if (item.file) {
        formData.append('files', item.file, item.name)
      }
    })

    const memberStore = useMemberStore()
    const userInfo = memberStore.profile
    const token = uni.getStorageSync('token')

    const xhr = new XMLHttpRequest()
    xhr.open('POST', `${envConfig.baseUrl}/receive/distributes/create-with-files`, true)

    if (token) {
      xhr.setRequestHeader('satoken', token)
      xhr.setRequestHeader('Authorization', `Bearer ${token}`)
    }

    if (userInfo && userInfo.id) {
      xhr.setRequestHeader('X-User-Id', String(userInfo.id))
      xhr.setRequestHeader('X-Username', encodeURIComponent(userInfo.username || ''))
      xhr.setRequestHeader(
        'X-Real-Name',
        encodeURIComponent(userInfo.nickname || userInfo.realName || userInfo.name || ''),
      )
      if (userInfo.companyId) {
        xhr.setRequestHeader('X-Company-Id', String(userInfo.companyId))
      }
      if (userInfo.companyName) {
        xhr.setRequestHeader('X-Company-Name', encodeURIComponent(userInfo.companyName || ''))
      }
    }

    xhr.onload = () => {
      if (xhr.status === 200) {
        try {
          const response = JSON.parse(xhr.responseText)
          resolve(response)
        } catch (e) {
          reject(new Error('响应解析失败'))
        }
      } else {
        reject(new Error(`上传失败: ${xhr.status}`))
      }
    }

    xhr.onerror = () => reject(new Error('网络错误'))
    xhr.send(formData)
  })
  // #endif

  // #ifndef H5
  // eslint-disable-next-line no-unreachable
  return Promise.reject(new Error('此函数仅支持H5'))
  // #endif
}

/**
 * APP/小程序上传（使用 yt-upload 内置上传 + 新接口）
 */
const uploadFilesApp = async (params: any): Promise<any> => {
  // #ifndef H5
  return new Promise((resolve, reject) => {
    // 🔍 调试日志：打印params详情
    console.log('[uploadFilesApp] 📤 准备上传，params详情:')
    console.log('  - sourceCompanyName:', params.sourceCompanyName)
    console.log('  - receiveDocumentSymbol:', params.receiveDocumentSymbol)
    console.log('  - 完整params:', JSON.stringify(params, null, 2))

    // 设置 formData（替换整个对象，而不是只设置 data 属性）
    const formDataToSend = { data: JSON.stringify(params) }
    ytUploadRef.value?.setData('formData', formDataToSend)
    console.log('[uploadFilesApp] 已设置 formData:', formDataToSend)

    // 多次设置确保生效（解决WebView更新延迟问题）
    setTimeout(() => {
      ytUploadRef.value?.setData('formData', formDataToSend)
      console.log('[uploadFilesApp] 第2次设置 formData（50ms后）')
    }, 50)

    setTimeout(() => {
      ytUploadRef.value?.setData('formData', formDataToSend)
      console.log('[uploadFilesApp] 第3次设置 formData（150ms后）')
    }, 150)

    // 设置上传状态
    // @ts-ignore
    uploadStatus.value.isUploading = true
    // @ts-ignore
    uploadStatus.value.uploadedCount = 0
    // @ts-ignore
    uploadStatus.value.totalCount = fileList.value.length
    // @ts-ignore
    uploadStatus.value.firstResponse = null
    // @ts-ignore
    uploadStatus.value.documentId = null
    // @ts-ignore
    uploadStatus.value.resolve = resolve
    // @ts-ignore
    uploadStatus.value.reject = reject

    // 延迟调用 upload，确保 setData 生效
    setTimeout(() => {
      console.log('[uploadFilesApp] 调用 yt-upload.upload()，开始上传')
      ytUploadRef.value?.upload()
    }, 300)

    // 超时保护
    setTimeout(() => {
      // @ts-ignore
      if (uploadStatus.value.isUploading) {
        console.error('[uploadFilesApp] 上传超时')
        // @ts-ignore
        uploadStatus.value.isUploading = false
        reject(new Error('上传超时'))
      }
    }, 120000)
  })
  // #endif

  // #ifdef H5
  // eslint-disable-next-line no-unreachable
  return Promise.reject(new Error('此函数仅支持APP'))
  // #endif
}

// 保存草稿
const saveDraft = async () => {
  if (!formData.sourceDocumentTitle.trim()) {
    uni.showToast({ title: '请填写文件标题', icon: 'none' })
    return
  }

  if (fileList.value.length === 0) {
    uni.showToast({ title: '请至少选择一个文件', icon: 'none' })
    return
  }

  try {
    uni.showLoading({ title: '保存中...' })

    const memberStore = useMemberStore()
    const userInfo = memberStore.profile

    if (!userInfo || !userInfo.id) {
      uni.showToast({ title: '用户信息不完整，请重新登录', icon: 'none' })
      uni.hideLoading()
      return
    }

    const params = {
      sourceCompanyName: formData.sourceCompanyName,
      receiveDocumentSymbol: formData.receiveDocumentSymbol,
      receiveDocumentNumber: formData.receiveDocumentNumber,
      receiveDocumentTime: formData.receiveDocumentTime
        ? `${formData.receiveDocumentTime}T00:00:00`
        : null,
      receiveDocumentTitle: formData.sourceDocumentTitle,
      receiveDocumentUrgencyLevel: formData.urgencyLevel,
      receiveDocumentSecurityLevel: formData.urgencyLevel,
      sourceDocumentTitle: formData.sourceDocumentTitle,
      sourceDocumentUrgencyLevel: formData.urgencyLevel,
      securityLevel: formData.urgencyLevel,
      operatorId: userInfo.id,
      operatorName: userInfo.nickname || userInfo.name || userInfo.username,
      unitType: 'external',
    }

    // 🔍 调试日志：打印准备上传的参数
    console.log('【调试】准备上传的params:', JSON.stringify(params, null, 2))
    console.log('【调试】来文单位:', formData.sourceCompanyName)
    console.log('【调试】文件字号:', formData.receiveDocumentSymbol)

    let response: any
    // #ifdef H5
    response = await uploadFilesH5(params)
    // #endif

    // #ifndef H5
    response = await uploadFilesApp(params)
    // #endif

    if (response && response.code === 200) {
      try {
        const bizId = response.data

        const draftResponse = await createReceiveDraft(bizId, {
          urgencyLevel: formData.urgencyLevel || 'normal',
          receiveNumber: formData.receiveDocumentNumber || '',
          title: formData.sourceDocumentTitle || '',
          type: 0,
          sourceCompanyName: formData.sourceCompanyName || '', // 添加来文单位
          receiveDocumentSymbol: formData.receiveDocumentSymbol || '', // 添加文件字号
          receiveDocumentTime: formData.receiveDocumentTime
            ? `${formData.receiveDocumentTime}T00:00:00`
            : null,
        })

        if (draftResponse && draftResponse.code === 200) {
          uni.showToast({ title: '登记成功', icon: 'success' })
          setTimeout(() => {
            uni.navigateBack({
              fail: () => {
                uni.reLaunch({ url: '/pages/index/index' })
              },
            })
          }, 1500)
        } else {
          throw new Error(draftResponse?.message || '确认登记失败')
        }
      } catch (draftError: any) {
        uni.showToast({
          title: '确认登记失败：' + (draftError.message || '未知错误'),
          icon: 'none',
          duration: 3000,
        })
      }
    } else {
      const errorMsg = (response as any)?.message || '文件上传失败'
      uni.showModal({
        title: '上传失败',
        content: `后端返回错误：${errorMsg}`,
        showCancel: false,
      })
      throw new Error(errorMsg)
    }
  } catch (error: any) {
    uni.showToast({
      title: error?.message || '保存失败',
      icon: 'none',
      duration: 3000,
    })
  } finally {
    uni.hideLoading()
  }
}

// 页面加载
onMounted(() => {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  formData.receiveDocumentTime = `${year}-${month}-${day}`
})
</script>

<style lang="scss" scoped>
.register-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 120rpx;

  .nav-header {
    background: #1a3582;
    padding: 46px 32rpx 20rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: white;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 99;

    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .nav-center {
      flex: 1;
      text-align: center;

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
      }
    }
  }

  .form-container {
    padding: 32rpx;
    margin-top: 88px;

    .form-card {
      background: white;
      border-radius: 16rpx;
      padding: 32rpx;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

      .card-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #1a3582;
        text-align: center;
        margin-bottom: 40rpx;
        padding-bottom: 16rpx;
        border-bottom: 2rpx solid #e5e7eb;
      }

      .form-item {
        display: flex;
        flex-direction: column;
        padding: 32rpx 0;
        border-bottom: 1rpx solid #e5e7eb;

        .form-label-wrapper {
          display: flex;
          flex-direction: column;
          gap: 8rpx;
          margin-bottom: 16rpx;
        }

        .form-label {
          font-size: 30rpx;
          color: #374151;
          font-weight: 500;
          margin-bottom: 16rpx;
        }

        .form-label-tip {
          font-size: 22rpx;
          color: #ef4444;
          line-height: 1.4;
          margin-top: -8rpx;
          margin-bottom: 12rpx;
        }

        .form-input-underline {
          width: 100%;
          height: 70rpx;
          line-height: 70rpx;
          padding: 0 16rpx;
          border: 1rpx solid #e5e7eb;
          border-radius: 8rpx;
          font-size: 30rpx;
          background: #f9fafb;
          box-sizing: border-box;
        }

        .form-textarea-underline {
          width: 100%;
          min-height: 140rpx;
          line-height: 1.8;
          padding: 16rpx;
          border: 1rpx solid #e5e7eb;
          border-radius: 8rpx;
          font-size: 30rpx;
          background: #f9fafb;
          box-sizing: border-box;
        }

        .picker-input-underline {
          width: 100%;
          height: 70rpx;
          line-height: 70rpx;
          padding: 0 16rpx;
          border: 1rpx solid #e5e7eb;
          border-radius: 8rpx;
          font-size: 30rpx;
          background: #f9fafb;
          display: flex;
          align-items: center;
          color: #374151;
          box-sizing: border-box;
        }

        .upload-section {
          width: 100%;

          .upload-btn-slot {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 120rpx;
            border: 2rpx dashed #d1d5db;
            border-radius: 12rpx;
            background: #f9fafb;

            .upload-icon {
              font-size: 32rpx;
              margin-right: 12rpx;
            }

            .upload-text {
              font-size: 28rpx;
              color: #6b7280;
            }
          }

          .file-list {
            margin-top: 16rpx;

            .file-item {
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 16rpx 24rpx;
              background: #f3f4f6;
              border-radius: 12rpx;
              margin-bottom: 12rpx;
              gap: 16rpx;

              .file-info {
                flex: 1;
                display: flex;
                flex-direction: column;
                gap: 8rpx;

                .file-name {
                  font-size: 26rpx;
                  color: #374151;
                  font-weight: 500;
                  word-break: break-all;
                }

                .file-size {
                  font-size: 22rpx;
                  color: #6b7280;
                }

                .file-status {
                  font-size: 22rpx;
                  padding: 4rpx 12rpx;
                  border-radius: 8rpx;
                  align-self: flex-start;

                  &.status-waiting {
                    color: #6b7280;
                    background: #e5e7eb;
                  }

                  &.status-loading {
                    color: #2563eb;
                    background: #dbeafe;
                  }

                  &.status-success {
                    color: #059669;
                    background: #d1fae5;
                  }

                  &.status-fail {
                    color: #dc2626;
                    background: #fee2e2;
                  }
                }
              }

              .file-delete {
                font-size: 32rpx;
                color: #ef4444;
                width: 40rpx;
                height: 40rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;
              }
            }
          }
        }
      }
    }
  }

  .bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #e5e7eb;
    display: flex;
    gap: 24rpx;

    .action-btn {
      flex: 1;
      height: 88rpx;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      &.cancel {
        background: #f3f4f6;
        border: 1rpx solid #d1d5db;

        .btn-text {
          color: #6b7280;
        }
      }

      &.primary {
        background: #1a3582;

        .btn-text {
          color: white;
        }
      }

      .btn-text {
        font-size: 32rpx;
        font-weight: 500;
      }
    }
  }
}
</style>
